package com.pxml2pdf.pdf;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.pxml2pdf.pdf.Node.BaseNode;
import com.pxml2pdf.pxml.Pxml;
import com.pxml2pdf.utility.FontUtility;

public class X2PConverter {
	public void Convert(Pxml pxmlObj, String fileName, String pdfpw) {
		FontUtility.registerFont();
		PageManger pm = new PageManger(pxmlObj);
		Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
		// System.out.println(PageSize.A4.getHeight());//842.0
		// System.out.println(PageSize.A4.getWidth());//595.0
		try {
			PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(new File(fileName)));
			if (pdfpw!=null && !"".equals(pdfpw)){
				writer.setEncryption(pdfpw.getBytes(), ("OWNER"+pdfpw).getBytes(), PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_256);
			}
			// writer.setStrictImageSequence(true);
			doc.open();
			doc.addAuthor("GovHRMS");
			doc.addCreationDate();
			doc.addTitle("GovHRMS Report");
			doc.addSubject("GovHRMS");
			makePage(writer, doc, pm);
			doc.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void makePage(PdfWriter writer, Document doc, PageManger pm) throws DocumentException, IOException {
		PdfContentByte cb = writer.getDirectContent();
		for (int pageIndex = 0; pageIndex < pm.getPageList().size(); pageIndex++) {
			PageInfo pi = pm.getPageInfo(pageIndex);
			doc.newPage();
			for (BaseNode ni : pi.getNodelist()) {
				PdfPTable table = ni.getTableInfo();
				if (table != null) {
					table.writeSelectedRows(0, -1, ni.getLlx(), ni.getUry(), cb);
				}
				ni.drawing(cb);
			}
			// BaseColor BACKGROUND_COLOR = new BaseColor(255, 255, 255);
			// cb.setLineWidth(0);
			// cb.setColorFill(BACKGROUND_COLOR);
			// cb.rectangle(0, 0, PageSize.A4.getWidth(),
			// PageManger.PAGE_TOP_OFF);
			// cb.fill();
			// cb.setLineWidth(0);
			// cb.setColorFill(BACKGROUND_COLOR);
			// cb.rectangle(0, PageManger.PAGE_TOP_MAX, PageSize.A4.getWidth(),
			// PageSize.A4.getHeight());
			// cb.fill();
		}
	}

}
